package com.example.cart.aop;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.LruCache;

import java.util.function.Consumer;

public class BitMapWorkerTask extends AsyncTask<BitMapWorkerTask.ImageSrcOperation, BitMapWorkerTask.BitMapOperation, BitMapWorkerTask.BitMapOperation> {

    /**
     * 设置为static并不合理，但是这里只是为了测试
     */
    private static LruCache<String, Bitmap> lruCache;

    public BitMapWorkerTask() {
        long size = Runtime.getRuntime().maxMemory() / 1024 / 8;

        lruCache = new LruCache<String, Bitmap>((int) size) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return value.getByteCount() / 1024;
            }
        };
    }

    @Override
    protected BitMapOperation doInBackground(ImageSrcOperation... imageOperations) {

        String src = imageOperations[0].src;
        Bitmap bitmap = lruCache.get(src);
        if (bitmap == null) {

            bitmap = BitmapFactory.decodeFile(src);
            lruCache.put(src,bitmap);
        }
        // publishProgress();
        return new BitMapOperation(bitmap, imageOperations[0].consumer);
    }

    @Override
    protected void onPostExecute(BitMapOperation bitMapOperation) {
        bitMapOperation.consumer.accept(bitMapOperation.bitmap);
    }

    public static class ImageSrcOperation {
        String src;
        Consumer<Bitmap> consumer;

        public ImageSrcOperation(String src, Consumer<Bitmap> consumer) {
            this.src = src;
            this.consumer = consumer;
        }
    }

    static class BitMapOperation {
        Bitmap bitmap;
        Consumer<Bitmap> consumer;

        public BitMapOperation(Bitmap bitmap, Consumer<Bitmap> consumer) {
            this.bitmap = bitmap;
            this.consumer = consumer;
        }
    }
}
